package com.demo.search.spring;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

import com.demo.search.service.SearchTaskService;
import com.demo.search.support.SearchTaskSupport;

/**
 * Spring管理的SearchTaskService
 * 该类将自动加载SearchTaskService与SearchTaskSupport。
 * 并将SearchTaskSupport按照配置读取顺序注入到SearchTaskService中。
 * 对于各应用中,无需考虑注入问题,直接配置实现SearchTaskSupport接口的对象将会被自动使用。
 * @author ryuu.kk
 *
 */
public class SpringSearchTaskProcessor implements BeanPostProcessor {

	/**
	 * 日志
	 */
	private static final Logger LOG = Logger.getLogger(SpringSearchTaskProcessor.class);

	/**
	 * 索引任务服务
	 */
	private SearchTaskService searchTaskService;
	
	/**
	 * 业务索引任务支持
	 */
	private List<SearchTaskSupport> searchTaskSupportList;
	
	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
		if (LOG.isDebugEnabled()) {
			LOG.debug(bean.getClass() + " had been created.");
		}
		return bean;
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof SearchTaskSupport) {
			if (searchTaskSupportList == null) {
				searchTaskSupportList = new ArrayList<SearchTaskSupport>();
			}
			if (searchTaskService != null) {
				if (LOG.isDebugEnabled()) {
					LOG.debug(bean.getClass() + " add into " + searchTaskService.getClass());
				}
				searchTaskService.addSupport((SearchTaskSupport) bean);
			} else {
				searchTaskSupportList.add((SearchTaskSupport) bean);
			}
		}
		if (bean instanceof SearchTaskService) {
			searchTaskService = (SearchTaskService) bean;
			if (searchTaskSupportList != null) {
				for (SearchTaskSupport support : searchTaskSupportList) {
					if (LOG.isDebugEnabled()) {
						LOG.debug(bean.getClass() + " add into " + searchTaskService.getClass());
					}
					searchTaskService.addSupport(support);
				}
			}
		}
		return bean;
	}
}
